using System.Diagnostics;
using FireStarter.Base;
using FireStarter.Base.BusinessObjectMerger;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.BO;

namespace FireStarterModeller.Logic.MergeBusinessObjects
{
    // This classes are used automatically by the MergeableBORegistry
    // ReSharper disable UnusedMember.Global 
    public class MergeDMObjectIdentity : MergeBO<DMObjectIdentity>
    {
        protected override void MergeMultipleRelationship(IMultipleRelationship fromMultipleRelationship, IMultipleRelationship toMultipleRelationship)
        {
            if (toMultipleRelationship == null || fromMultipleRelationship == null) return;
            if (fromMultipleRelationship.RelationshipName != "Properties") return;
            //This has to be done in the MergeMultiple Relationship and not the MergeBOCol because
            // this needs to get the DMProperty from the DMClass that is associated with the Unique Constraint.
            DMObjectIdentity toOId = (DMObjectIdentity) toMultipleRelationship.OwningBO;
            var fromDMProps = fromMultipleRelationship.BusinessObjectCollection;
            var toDMProps = toMultipleRelationship.BusinessObjectCollection;
            while (toDMProps.Count > 0)
            {
                toDMProps.Remove(toDMProps[0]);
            }
            foreach (DMProperty fromDMProp in fromDMProps)
            {
                if (toOId.Class == null) continue;
                IDMProperty property  = toOId.Class.GetDMProperty(fromDMProp.PropertyName);
                if(property == null)
                {
                    property = new DMProperty();
                    var mergeProp = MergeableBORegistry.Instance.Resolve<DMProperty>();
                    mergeProp.MergeBOFrom(fromDMProp, (IMergableBo)property);
                    toOId.Class.Properties.Add((DMProperty)property);
                }
                toDMProps.Add(property);
            }
        }
        //The Properties relationship is not composite and therefore will not be merged by default.
        public override bool MustMergeRelationship(IRelationship relationship)
        {
            if (relationship.RelationshipName == "Properties") return true;
            return base.MustMergeRelationship(relationship);
        }
    }
    // ReSharper restore UnusedMember.Global
}